package org.example.sync_compare_reen;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 对比synchronized和reentrent
 */
public class TestCompare {
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static CountDownLatch countDownLatch = new CountDownLatch(1000);
    private static int n = 0;
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                syncTest();
//                reenTest();
            }).start();
        }
        countDownLatch.await();
        System.out.println(System.currentTimeMillis()-start);
    }

    public static void syncTest(){
        for (int i = 0; i < 1000_0000; i++) {
            synchronized (reentrantLock){
                n++;
            }
        }
        countDownLatch.countDown();
    }

    public static void reenTest(){
        for (int i = 0; i < 1000_0000; i++) {
            try {
                reentrantLock.lock();
                n++;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }
        countDownLatch.countDown();
    }
}
